
const baseUrl = 'http://localhost:3000'; // 接口地址路径
import Mock from 'mockjs'
// 请求配置
const config = {
  baseUrl,
  timeout: 10000, // 超时时间
  showLoading: true, // 默认显示loading
};
 
// 请求拦截器
const requestInterceptor = (options) => {
  if (config.showLoading) {
    uni.showLoading({ title: '加载中...', mask: true });
  }
  
  // 统一添加token
  const token = uni.getStorageSync('token');
  if (token) {
    options.header = {
      ...options.header,
      'Authorization': `${token}`,
    };
  }
  return options;
};
 
// 响应拦截器
const responseInterceptor = (response, resolve, reject) => {
  if (config.showLoading) {
    uni.hideLoading();
  }
  
  const { statusCode, data } = response;
  if (statusCode === 200) {
    if (data.code === 200) { // 假设业务成功code为0
      resolve(data);
    } else {
      uni.showToast({ title: data.message || '请求失败', icon: 'none' });
      reject(data);
    }
  } else if (statusCode === 401) { // token过期
    uni.navigateTo({ url: '/pages/login/index' });
    reject(new Error('未登录'));
  } else {
    uni.showToast({ title: `请求错误: ${statusCode}`, icon: 'none' });
    reject(new Error('网络异常'));
  }
};
 
// 核心请求方法
const request = (options = {}) => {
  return new Promise((resolve, reject) => {
    options = {
      ...config,
      // ...options,
      url: `${config.baseUrl}${options.url}`,
	  // url: `${options.url}`,
      header: { 'Content-Type': 'application/json', ...options.header },
    };
    
    try {
      options = requestInterceptor(options); // 请求前处理
    } catch (err) {
      reject(err);
    }
 
    uni.request({
      ...options,
      success: (res) => {
        responseInterceptor(res, resolve, reject);
      },
      fail: (err) => {
        if (config.showLoading) uni.hideLoading();
        uni.showToast({ title: '网络连接失败', icon: 'none' });
        reject(err);
      },
      complete: () => {
        options.showLoading = false; // 防止多次hide
      }
    });
  });
};
 
// 快捷方法封装
const get = (url, data = {}, options = {}) => {
  return request({ url, data, method: 'GET', ...options });
};
 
const post = (url, data = {}, options = {}) => {
  return request({ url, data, method: 'POST', ...options });
};
 


export default { request, get, post };
